package cn.swing.his.common.utils;


import com.alibaba.fastjson.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
@Slf4j
public class QnyUtils {
    @Value("${qi-niu-yun.accessKey}")
    private String accessKey;
    @Value("${qi-niu-yun.secretKey}")
    private String secretKey;
    @Value("${qi-niu-yun.bucket}")
    private String bucket;

    public boolean upload(MultipartFile file, String fileName){
        Configuration cfg = new Configuration();
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey,secretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(uploadBytes,fileName,upToken);
            // 解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(),DefaultPutRet.class);
            log.info( "putRet KEY" + putRet.key);
            log.info("putRet HASH" + putRet.hash);
            return true;
        } catch (Exception e) {
        }
        return false;
    }
}
